import json
import requests
from faker import Faker
from datetime import datetime
import hashlib

host = 'http://121.11.97.201:9088/'


def generate_md5(str):
    # 生成 MD5 签名
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    signature = md5.hexdigest()
    return signature


def generate_md5_signature(params, secret_key):
    """
    生成 MD5 签名

    :param params: 需要签名的参数字典
    :param secret_key: 秘钥
    :return: MD5 签名字符串
    """
    # 将参数字典按字典序排序并转换为字符串
    sorted_params = sorted(params.items(), key=lambda item: item[0])
    query_string = '&'.join([f"{key}={value}" for key, value in sorted_params])

    # 将秘钥添加到字符串的末尾
    query_string_with_secret = f"{query_string}&key={secret_key}"

    # 生成 MD5 签名
    md5 = hashlib.md5()
    md5.update(query_string_with_secret.encode('utf-8'))
    signature = md5.hexdigest()

    return signature

def test_post_md5():
    url = host + '/pinter/com/userInfo'
    fake = Faker('zh_CN')
    # 生成毫秒级时间戳
    timestamp = int(datetime.now().timestamp() * 1000)
    params = {
        "phoneNum": fake.phone_number(),
        "optCode": "testfan",
        "timestamp": timestamp
    }
    secret_key = "your_secret_key"  # 替换为实际的秘钥
    params['sign'] = generate_md5_signature(params, secret_key)

    response = requests.post(url=url, json=params)  # 默认追加了json头部
    # 检查响应状态码
    if response.status_code == 200:
        print("请求成功")
        # 获取响应内容
        data = response.json()  # 假设响应是JSON格式
        print("响应数据:", data)
    else:
        print("请求失败，状态码:", response.status_code)
    rest = response.json()
    assert response.status_code == 200
    assert rest['code'] == '0'

if __name__ == '__main__':
    # test_request_get1()
    # test_request_get4()
    test_post_md5()
    # test_request_get2()
    # test_request_get3()
    # test_post_test1()
    # test_post_test2()
